package net.tatu.service.impl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.tatu.dao.UserMapper;
import net.tatu.model.User;
import net.tatu.service.UserService;
import net.tatu.util.Encrypt;
import net.tatu.util.Util;

@Service
public class UserServiceImpl implements UserService {
	Logger log = Logger.getLogger(UserServiceImpl.class);
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public User register(User user) {
		
		String pwd = Encrypt.md5(user.getUserPassword());
		log.debug("input databases pwd:" + pwd.length());
		user.setUserPassword(pwd);
		user.setRecordStatusCode(1);
		int u = userMapper.insertUser(user);
		if (u != 1) {
			return null;
		}
		log.debug("user back:" + user.toString());
		return userMapper.get(user);
	}

	@Override
	public User login(User user) {
		
		User u = userMapper.get(user);
		if (u == null) {
			return null;
		}
		String pwd = Encrypt.md5(user.getUserPassword());
		log.debug("input pwd:" + pwd);
		log.debug("table pwd:" + u.getUserPassword());
		if (u.getUserPassword().equals(pwd) && 1==u.getRecordStatusCode()) {
			return u;
		}
		return null;
	}

	@Override
	public User loginResetPassword(User user) {
		
		User u = userMapper.get(user);
		if (u == null) {
			return null;
		}
//		String pwd = Encrypt.md5(user.getUserPassword());
//		log.debug("input pwd:" + pwd);
//		log.debug("table pwd:" + u.getUserPassword());
		if (1==u.getRecordStatusCode()) {
			return u;
		}
		return null;
	}
	
	@Override
	public void addUser(String name) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public User get(User user) {
		
		User u = userMapper.get(user);
		if (u == null) {
			return null;
		}
		if (1 == u.getRecordStatusCode()) {
			return u;
		}
		return null;
	}

	@Override
	public String verifyUser(User user) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean updateUser(User user) {
		boolean ret = false;
		int i = userMapper.updateUser(user);
		log.debug("更新用户时的返回结果：" + i);
		if(i == 1){
			ret = true;
		}
		return ret;
	}

	@Override
	public User getById(long userId) {
		User user = new User();
		user.setUserId(userId);
		User u = userMapper.get(user);
		
		return u;
	}

	@Override
	public boolean isExistUser(String mobileFront) {
		boolean ret = false;
		User user = new User();
		user.setUserMobile(mobileFront);
		User u = userMapper.get(user);
		if(null != u){
			ret = true;
		}
		return ret;
	}
	
	@Override
	public boolean isExistUserEmail(String email) {
		boolean ret = false;
		User user = new User();
		user.setUserEmail(email);
		User u = userMapper.get(user);
		if(null != u){
			ret = true;
		}
		return ret;
	}
}
